package com.adtec.base.cloud.server.gateway.filter.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

public class GetIpAddressUtil {

    public static String getIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String XFor  = headers.getFirst("X-Forwarded-For");
        //System.out.println("X-Forwarded-For="+XFor);
//        String For  = headers.getFirst("X-FORWARDED-FOR");
        //System.out.println("X-FORWARDED-FOR="+For);
//        String Xor  = headers.getFirst("x-forwarded-for");
        //System.out.println("x-forwarded-for="+Xor);
        String Xip   = headers.getFirst("X-Real-IP");
        //System.out.println("X-Real-IP="+Xip);
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = headers.getFirst("Proxy-Client-IP");
            //System.out.println("Proxy-Client-IP="+XFor);
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = headers.getFirst("WL-Proxy-Client-IP");
            //System.out.println("WL-Proxy-Client-IP="+XFor);
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = headers.getFirst("HTTP_CLIENT_IP");
            //System.out.println("HTTP_CLIENT_IP="+XFor);
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = headers.getFirst("HTTP_X_FORWARDED_FOR");
            //System.out.println("HTTP_X_FORWARDED_FOR="+XFor);
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddress().getAddress().getHostAddress();
            //System.out.println("HostAddress="+XFor);
        }
        return XFor.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : XFor;
    }
}
